<template>
    <el-dialog :title="dialogFrom.dialogTitle" :model-value="dialogFrom.dialogVisible" class="user-ruleForm"
        @input:model-value="updateDialogVisible" align-center width="60%" :before-close="onCancel">
        <el-form ref="unifiedFormRef" :model="userRoleInfo" :rules="rules" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="dataInfo.username" placeholder="请填写用户名" disabled clearable></el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="nickName">
                <el-input v-model="dataInfo.nickName" placeholder="请填写昵称" disabled clearable></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
                <el-input v-model="dataInfo.phone" placeholder="请填写电话" disabled :maxlength="11" clearable></el-input>
            </el-form-item>
            <el-form-item label="角色" prop="roleIds">
                <el-select v-model="userRoleInfo.roleIds" placeholder="请选择角色" multiple
                    class="user-role-select-multiple">
                    <el-option v-for="(item, index) in selectRoleList" :key="index" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="onSubmit(unifiedFormRef)">提交</el-button>
                <el-button @click="onCancel">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
// -------------------------------------------------导入相关引用-------------------------------------------------

import { ref, watch } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import type { DataInfo } from '@/api/system/SysUser'
import { getInfo, editUserRole, listUserRole } from '@/api/system/SysUser'
import { getList as getRoleList, type TableData as RoleTableData } from '@/api/system/SysRole'
// -------------------------------------------------相关参数定义-------------------------------------------------
const props = withDefaults(defineProps<{
    dialogFrom: DialogFrom
}>(), {
    dialogFrom: () => ({
        dialogTitle: '',
        dialogVisible: false,
        infoId: null,
    })
});

const unifiedFormRef = ref<FormInstance | undefined>(undefined);

const rules: FormRules = {
    roleIds: [
        { required: true, message: '请选择角色', trigger: 'change' },
    ],
}

const dataInfo = ref<DataInfo>({
    id: null,
    username: '',
    password: '',
    nickName: '',
    phone: '',
    email: '',
    address: '',
    profilePicture: '',
})

const selectRoleList = ref<RoleTableData[]>([]);

const userRoleInfo = ref<{
    roleIds: number[],
    userId: number | null
}>({
    roleIds: [],
    userId: null
})

// ---------------------------------------------------事件定义--------------------------------------------------

const emit = defineEmits(['update:dialogFrom', 'onParentSearch']);

// -------------------------------------------------操作方法定义-------------------------------------------------

/**
 * 监听dialogFrom参数
 */
watch(() => props.dialogFrom.dialogVisible, (newValue, oldValue) => {
    if (newValue) {
        getRoleListApi();
        getInfoApi();
        listUserRoleApi();
    }
})

const getRoleListApi = async () => {
    await getRoleList().then((res) => {
        if (res.data.code === 200) {
            selectRoleList.value = res.data.data;
        }
    })
}

const listUserRoleApi = async () => {
    if (!props.dialogFrom.infoId) return;
    await listUserRole({ userId: props.dialogFrom.infoId, roleId: null }).then((res) => {
        if (res.data.code === 200) {
            userRoleInfo.value.roleIds = res.data.data.map((item: { roleId: number, userId: number }) => {
                return item.roleId;
            })
        }
    })
}

/**
 * 获取表单信息
 */
const getInfoApi = async () => {
    const infoId = props.dialogFrom.infoId;
    if (infoId) {
        await getInfo(infoId).then((res) => {
            if (res.data.code === 200) {
                dataInfo.value = res.data.data;
            }
        })
    }
}

/**
 * 提交表单
 */
const onSubmit = async (ref: FormInstance | undefined) => {
    if (!ref) return
    await ref.validate((valid, fields) => {
        if (valid) {
            userRoleInfo.value.userId = dataInfo.value.id;
            editUserRole(userRoleInfo.value).then((res) => {
                if (res.data.code === 200) {
                    ElMessage.success({
                        message: '角色分配成功',
                        type: 'success'
                    })
                    onCancel();
                }
            })
        }
    })
}

/**
 * 关闭弹窗
 */
const onCancel = () => {
    resetFrom();
    emit('update:dialogFrom', {
        dialogVisible: false,
        dialogTitle: '',
        infoId: null
    });
    emit('onParentSearch');
}

/**
 * 重置表单
 */
const resetFrom = () => {
    dataInfo.value = {
        id: null,
        username: '',
        password: '',
        nickName: '',
        phone: '',
        email: '',
        address: '',
        profilePicture: '',
    }
    userRoleInfo.value = {
        roleIds: [],
        userId: null
    }
}

/**
 * 更新弹窗显示状态
 * @param dialogFromParams
 * @returns void
 */
const updateDialogVisible = (dialogFromParams: DialogFrom) => {
    emit('update:dialogFrom', dialogFromParams);
}

// -------------------------------------------------实体定义区-------------------------------------------------

/**
 * 弹窗信息
 */
export interface DialogFrom {
    dialogTitle: string;
    dialogVisible: boolean;
    infoId: number | null;
}
</script>

<style lang="scss" scoped>
.user-avatar-uploader .user-avatar {
    width: 120px;
    height: 120px;
    display: block;
}

.user-role-select-multiple {
    :deep() .el-select__selected-item {
        border: 1px solid var(--el-border-color);
    }

    :deep() .el-select__placeholder {
        border: unset;
    }

}
</style>

<style>
.user-avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.user-avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.user-avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
}
</style>